﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.Reflection;

namespace SnippetPlugin.Data {
    [DataContract]
    public class Config {
        /*
        private bool _runSilent = false;
        [DataMember]
        public bool RunSilent {
            get { return _runSilent; }
            set { _runSilent = value; }
        }
         * */

        private List<Data.Snippet> _snippets;
        [DataMember]
        public List<Data.Snippet> Snippets {
            get { return _snippets; }
            set { _snippets = value; }
        }

        private static string configFile {
            get { return (Assembly.GetExecutingAssembly().Location + ".config"); }
        }

        public static Config Load() {
            Config config;
            FileStream fs = null;
            if(File.Exists(configFile)) {
                fs = new FileStream(configFile, FileMode.Open);
            }
            if(fs != null) {
                DataContractSerializer ser = new DataContractSerializer(typeof(Config));
                config = ser.ReadObject(fs) as Config;
                fs.Close();
            } else {
                config = new Config();
            }
            config.EnsureInit();
            return config;
        }

        public void EnsureInit() {
            if(Snippets == null) {
                Snippets = new List<Snippet>();
            }
        }

        public void Save() {
            FileStream fs = new FileStream(configFile, FileMode.OpenOrCreate);
            if(fs != null) {
                fs.SetLength(0);
                DataContractSerializer ser = new DataContractSerializer(typeof(Config));
                ser.WriteObject(fs, this);
                fs.Close();
            }
        }
    }
}
